package com.example.service.impl;

import com.example.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: 21050134
 * @date: 2023/10/8 11:59
 * @description:
 */
@Service
public class DeptServiceImpl implements DeptService {

	private static Integer count =1000000;


	@Override
	public String deptInfo_Ok(Integer id) {
		return "线程池：" + Thread.currentThread().getName() + " deptInfo_Ok,id: "+ id;
	}

	@Override
	@HystrixCommand(fallbackMethod = "dept_TimeoutHandler",
			//超过5秒，调用指定方法
			commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value ="5000")})
	public String deptInfo_Timeout(Integer id) {
		int outTime =4;
		try{
			TimeUnit.SECONDS.sleep(outTime);
		}catch (InterruptedException e){
           e.printStackTrace();
		}
		return "线程池：" + Thread.currentThread().getName() + "  deptInfo_Timeout,id:   " + id + "  耗时: " + outTime;
	}

	public String dept_TimeoutHandler(Integer id){
		return "系统繁忙请稍后再试！线程池：" +Thread.currentThread().getName() + " deptInfo_Timeout,id: "+ id;
	}

	//Hystrix 熔断案例
    @Override
    @HystrixCommand(fallbackMethod = "deptCircuitBreaker_fallback",commandProperties = {
           //以下参数在 HystrixCommandProperties 类中有默认配置
		    @HystrixProperty(name ="circuitBreaker.enabled",value = "true"),//是否开启熔断器
		    @HystrixProperty(name ="metrics.rollingStats.timeInMilliseconds",value = "10000"),//统计时间窗
		    @HystrixProperty(name ="circuitBreaker.requestVolumeThreshold",value = "5"),//统计时间窗内请求次数
		    @HystrixProperty(name ="circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//休眠时间窗口期
		    @HystrixProperty(name ="circuitBreaker.errorThresholdPercentage",value = "60"),//在统计时间窗口期以内，请求失败率达到 60% 时进入熔断状态
    })
    public String deptCircuitBreaker(Integer id){
		if(id<0){
			throw new RuntimeException("id不能为负数");
		}
		return Thread.currentThread().getName() +"调用成功，流水号为：" + (count++);
    }

    //deptCircuitBreaker 的降级方法
    public String deptCircuitBreaker_fallback(Integer id){
	    return "id 不能是负数,请稍后重试!\t id:" + id;
    }


}
